package com.cloud.gateway.config;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient.Builder;
import org.springframework.web.reactive.function.server.ServerResponse;

import java.time.Instant;
import java.util.Map;

@Configuration
public class SentinelGatewayConfig {

//    @Autowired
//    private FallbackService fallbackService;
//    @Autowired
//    private Builder webClientBuilder;
//    @PostConstruct
//    public void init() {
//        GatewayCallbackManager.setBlockHandler((exchange, t) -> {
//            // 根据请求路径动态选择备用接口
//            String path = exchange.getRequest().getPath().toString();
////            String fallbackUrl = fallbackService.getFallbackUrl(path);
//
//            return webClientBuilder.build()
//                    .get()
//                    .uri("http://fallback-service/api/fallback") // 备用接口地址
////                    .uri(fallbackUrl)
//                    .retrieve()
//                    .bodyToMono(String.class)
//                    .flatMap(response -> {
//                        return ServerResponse.ok()
//                                .contentType(MediaType.APPLICATION_JSON)
//                                .bodyValue(response);
//                    });
//        });
//    }
    @PostConstruct
    public void init() {
        // 强制覆盖 Sentinel 默认的限流处理器
        GatewayCallbackManager.setBlockHandler((exchange, ex) -> {
            exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
            exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);

            Map<String, Object> response = Map.of(
                    "code", 429,
                    "message", "请求过于频繁，请稍后再试",
                    "path", exchange.getRequest().getPath().toString(),
                    "timestamp", Instant.now().toString()
            );

            return ServerResponse
                    .status(HttpStatus.TOO_MANY_REQUESTS)
                    .bodyValue(response);
        });
    }
}